package com.kfpanda.spring.batch.incrementer.h2;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersIncrementer;
import org.springframework.stereotype.Repository;

import com.kfpanda.spring.batch.incrementer.Incrementer;
import com.kfpanda.spring.batch.incrementer.JdbcIncrement;

@Repository("h2Incrementer")
public class H2Incrementer implements JobParametersIncrementer {
	
	@Resource(name = "h2JdbcIncrement")
	private JdbcIncrement<?> jdbcIncrement;
	
    public JobParameters getNext(JobParameters parameters) {
    	H2IncrementBean incremBean = (H2IncrementBean) jdbcIncrement.findIncrementer(parameters);
    	String beforeIncrem = StringUtils.isBlank(incremBean.getBeforeIncrementer()) ?
    				incremBean.getIncrementer() : incremBean.getBeforeIncrementer();
    	JobParametersBuilder paramBuilder = new JobParametersBuilder(parameters);
    	paramBuilder.addString(Incrementer.BEFORE_INCREMENTER_NAME, beforeIncrem);
    	paramBuilder.addString(
    			Incrementer.INCREMENTER_NAME, incremBean.getIncrementer());
    	
        return paramBuilder.toJobParameters();
    }

	public JdbcIncrement<?> getJdbcIncrement() {
		return jdbcIncrement;
	}

	public void setJdbcIncrement(JdbcIncrement<?> jdbcIncrement) {
		this.jdbcIncrement = jdbcIncrement;
	}
    
}
